package lq.demo.springbootmybatis.demo.common.aspect;

import lq.demo.springbootmybatis.demo.common.annotation.Log;
import lq.demo.springbootmybatis.demo.entity.MyLog;
import lq.demo.springbootmybatis.demo.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @program: comment-demo
 * @description:
 * @author: LQ
 * @create: 2020-09-07 09:51
 */

/**
 * 首先定义一个切面类
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    LogService logService;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(lq.demo.springbootmybatis.demo.common.annotation.Log)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveLog(point, time);
        //保存日志
        return result;
    }

    @Autowired
    MyLog logInfo;

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        logInfo.setExecuteTime(time);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log log = method.getAnnotation(Log.class);
        String operation = "";
        if (log != null) {
            //注解上的描述
            operation = log.value();
            logInfo.setOperation(operation);
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        logInfo.setClassName(className);
        logInfo.setMethodName(methodName);

        //attributes可以获取request信息 session信息等
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logInfo.setRequestMethod(request.getMethod());
        logService.addLog(logInfo);
    }
}
